package cn.yangphere.web.action.product;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.stereotype.Controller;

import cn.yangphere.bean.product.Brand;
import cn.yangphere.service.product.BrandService;
import cn.yangphere.web.formbean.product.BrandForm;

@Controller("/control/brand/manage")
public class BrandManageAction extends DispatchAction {

	@Resource(name = "brandServiceBean")
	private BrandService brandService;

	/**
	 * 品牌添加界面
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward addUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("add");
	}

	/**
	 * 品牌添加
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		BrandForm formBean = (BrandForm) form;
		Brand brand = new Brand();
		brand.setName(formBean.getName());
		
		if(formBean.getLogoFile()!=null && formBean.getLogoFile().getFileSize()>0){
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd/HH");		
			String logoPathDir = "/images/brand/" + dateFormat.format(new Date());
			String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);
			File logoSaveDir = new File(logoRealPathDir);
			if(!logoSaveDir.exists()){
				logoSaveDir.mkdirs();
			}
			String ext = formBean.getLogoFile().getFileName()
				.substring(formBean.getLogoFile().getFileName().lastIndexOf("."));
			String imageName = UUID.randomUUID().toString() + ext;
			FileOutputStream fileOutStream = new FileOutputStream(new File(logoSaveDir, imageName));
			fileOutStream.write(formBean.getLogoFile().getFileData());
			fileOutStream.close();
			
			String logoPath = logoPathDir + "/" + imageName;
			brand.setLogoPath(logoPath);
		}
		
		
		brandService.save(brand);
		
		request.setAttribute("message", "添加品牌成功");
		return mapping.findForward("message");
	}
}
